import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/widgets/animate/animate_view.dart';

///弹出窗口
class PopupWindow extends StatefulWidget {
  ///主界面
  final Widget child;

  ///控制器
  final PopupWindowController? controller;

  /// 弹出层界面
  final Widget Function(PopupWindowController controller)? buildPopup;

  /// 关闭回调
  final Function(dynamic data)? onDismiss;

  /// 弹出层偏移
  final double offset;

  /// 弹出层的方向
  final PopupDirection direction;

  /// 是否需要动画
  final bool? needAnimate;

  /// 弹出层透明部分颜色
  final Color bgColor;

  /// 点击透明或者空白部分是否关闭弹出层
  final bool closePopupClickOutside;

  /// 弹出层的大小
  final double? size;

  const PopupWindow({
    super.key,
    required this.child,
    this.controller,
    this.buildPopup,
    this.onDismiss,
    this.offset = 0,
    this.direction = PopupDirection.top,
    this.needAnimate = true,
    this.bgColor = const Color(0x30000000),
    this.closePopupClickOutside = true,
    this.size = 200,
  });

  @override
  State<StatefulWidget> createState() => _PopupWindowState();
}

class _PopupWindowState extends State<PopupWindow> {
  late PopupWindowController _controller;
  bool _open = true;
  bool? _visible;
  dynamic _data;
  bool _isNeedFlashEveryTime = false;

  @override
  void initState() {
    super.initState();
    _controller = widget.controller ?? PopupWindowController();
    _controller._state = this;
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        widget.child,
        Visibility(
          visible: _visible ?? false,
          child: _buildPopupWindow(),
        ),
      ],
    );
  }

  Widget _buildPopupWindow() {
    return GestureDetector(
      onTap: () {
        if (widget.closePopupClickOutside) {
          _controller.close();
        }
      },
      child: Container(
        width: double.infinity,
        height: double.infinity,
        color: Colors.transparent,
        child: Container(
          margin: widget.direction == PopupDirection.top
              ? EdgeInsets.only(top: widget.offset)
              : widget.direction == PopupDirection.bottom
                  ? EdgeInsets.only(bottom: widget.offset)
                  : widget.direction == PopupDirection.left
                      ? EdgeInsets.only(left: widget.offset)
                      : widget.direction == PopupDirection.right
                          ? EdgeInsets.only(right: widget.offset)
                          : EdgeInsets.only(top: widget.offset),
          child: Stack(
            alignment: widget.direction == PopupDirection.top
                ? AlignmentDirectional.topCenter
                : widget.direction == PopupDirection.bottom
                    ? AlignmentDirectional.bottomCenter
                    : widget.direction == PopupDirection.left
                        ? AlignmentDirectional.centerStart
                        : widget.direction == PopupDirection.right
                            ? AlignmentDirectional.centerEnd
                            : AlignmentDirectional.topCenter,
            children: [
              Container(
                width: double.infinity,
                height: double.infinity,
                color: widget.bgColor,
              ),
              ClipRect(
                child: GestureDetector(
                  onTap: () {},
                  child: AnimateView(
                    isNeedFlashEveryTime: _isNeedFlashEveryTime,
                    animate: TranslationAnimate(
                      type: _open
                          ? TranslationAnimateType.translateIn
                          : TranslationAnimateType.translateOut,
                      angle: widget.direction == PopupDirection.top
                          ? (_open
                              ? TranslationAnimateDirection.bottomToTop.angle
                              : TranslationAnimateDirection.topToBottom.angle)
                          : widget.direction == PopupDirection.bottom
                              ? (_open
                                  ? TranslationAnimateDirection
                                      .topToBottom.angle
                                  : TranslationAnimateDirection
                                      .bottomToTop.angle)
                              : widget.direction == PopupDirection.left
                                  ? (_open
                                      ? TranslationAnimateDirection
                                          .rightToLeft.angle
                                      : TranslationAnimateDirection
                                          .leftToRight.angle)
                                  : widget.direction == PopupDirection.right
                                      ? (_open
                                          ? TranslationAnimateDirection
                                              .leftToRight.angle
                                          : TranslationAnimateDirection
                                              .rightToLeft.angle)
                                      : (_open
                                          ? TranslationAnimateDirection
                                              .bottomToTop.angle
                                          : TranslationAnimateDirection
                                              .topToBottom.angle),
                      callback: (status) {
                        if (status == AnimationStatus.completed) {
                          _isNeedFlashEveryTime = false;
                        }
                        if (!_open && status == AnimationStatus.completed) {
                          _visible = false;
                          widget.onDismiss?.call(_data);

                          ///清除选择数据，防止未选择时关闭弹窗会发送上一次数据
                          _data = null;
                          _update();
                        }
                      },
                      duration: 200,
                    ),
                    child: SizedBox(
                      width: widget.direction == PopupDirection.top ||
                              widget.direction == PopupDirection.bottom
                          ? double.infinity
                          : widget.size,
                      height: widget.direction == PopupDirection.left ||
                              widget.direction == PopupDirection.right
                          ? double.infinity
                          : widget.size,
                      child:
                          widget.buildPopup?.call(_controller) ?? Container(),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  _update() {
    setState(() {});
  }
}

///控制器
class PopupWindowController {
  _PopupWindowState? _state;

  ///打开弹出层
  open() {
    _state?._open = true;
    _state?._visible = true;
    _state?._isNeedFlashEveryTime = true;
    _state?._update();
  }

  ///设置数据
  setData(dynamic data) {
    _state?._data = data;
  }

  ///关闭弹出层
  close() {
    _state?._open = false;
    _state?._isNeedFlashEveryTime = true;
    _state?._update();
  }
}

///弹出层弹出的方向
enum PopupDirection {
  left,
  right,
  top,
  bottom,
}
